const send = async (url, method, data) => {
    const response = await fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    });
    return response.json();
};

if (document.forms['login']) {
    document.forms['login'].addEventListener('submit', async (e) => {
        e.preventDefault();
        const email = e.target.querySelector('input#email').value;
        const password = e.target.querySelector('input#password').value;
        const response = await send('/api/login', 'POST', { email, password });
        if (response.id) {
            window.location.href = '/index.php';
        } else {
            const notification = document.querySelector('#notification');
            notification.textContent = 'Invalid credentials';
        }
    });
}

if (document.forms['register']) {
    document.forms['register'].addEventListener('submit', async (e) => {
        e.preventDefault();
        const email = e.target.querySelector('input#email').value;
        const password = e.target.querySelector('input#password').value;
        const firstName = e.target.querySelector('input#firstName').value;
        const lastName = e.target.querySelector('input#lastName').value;
        const response = await send('/api/register', 'POST', { email, password, firstName, lastName });
        console.log(response);
        if (response.id) {
            window.location.href = '/login.php';
        } else {
            const notification = document.querySelector('#notification');
            notification.textContent = 'Invalid credentials';
        }
    });
}
